/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.Receita_CRUD;
import Model.Usuario;
import Util.HibernateUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;

/**
 *
 * @author aluno
 */
@WebServlet(name = "ServletUsuario", urlPatterns = {"/ServletUsuario"})
public class ServletUsuario extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Usuario user = (Usuario) session.getAttribute("user");
        String opt = (String) request.getParameter("opt");
        String url = "";
        ArrayList myrecs;
        switch (opt) {
            case "detalhes":
                if (user != null) {
                    myrecs = Receita_CRUD.getmyrecs(request, "no", user);
                    session.setAttribute("myrecs", myrecs);
                }

                url = "main.jsp";
                break;
            case "cad":
                editUsuario(request);
                url = "cadastro_de_usuario.jsp";
                break;
            case "insert":
                insertUsuario(request);
                String edit = request.getParameter("edit");
                if (edit == null) {
                    url = "identificacao.jsp";
                } else if (edit.equals("yes")) {
                    url = "main.jsp";
                }

                break;
            case "identify":
                if (identify(request)) {
                    if (user != null) {
                        myrecs = Receita_CRUD.getmyrecs(request, "yes", (Usuario) session.getAttribute("user"));
                        session.setAttribute("myrecs", myrecs);
                    }
                    url = "main.jsp";
                } else {
                    url = "identificacao.jsp";
                    request.setAttribute("id", "false");
                }
                break;
            case "login":
                url = "identificacao.jsp";
                break;
            case "deletar":
                deletarUsuario(request);
                session.setAttribute("users", listUsers());
                url = "gerenciamento.jsp";
                break;
            case "adm":
                session.setAttribute("recs", Receita_CRUD.listReceitas());
                session.setAttribute("users", listUsers());
                url = "gerenciamento.jsp";
                break;
            case "logout":
                logout(request);
                url = "identificacao.jsp";
                break;
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    private void insertUsuario(HttpServletRequest request) {
        Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
        Usuario user = (Usuario) request.getSession().getAttribute("user");
		String login_user = "";
        if (user == null) {
            user = new Usuario();
		}else{
			login_user = user.getLogin();
		}

        String name = (String) request.getParameter("name");
        String city = (String) request.getParameter("city");
        String phone = (String) request.getParameter("telephone");
        String email = (String) request.getParameter("email");
        String pass = (String) request.getParameter("pass");
        String state = (String) request.getParameter("state");

        user.setName(name);
        user.setCity(city);
        user.setPhone(phone);
        user.setLogin(email);
        user.setPassword(pass);
        user.setState(state);

        hSession.beginTransaction();

        int result = (int) (long) hSession.createQuery("SELECT count(u.id) FROM Usuario u WHERE u.login = :login")
                .setParameter("login", email).uniqueResult();

        if (result == 0) {
            hSession.save(user);
        } else {
            if (user.getLogin().equals(login_user)) {
                request.getSession().setAttribute("user", user);
                request.getSession().removeAttribute("usuario");
            }
            else{
                int id = (int) hSession.createQuery("SELECT u.id FROM Usuario u WHERE u.login = :login")
                .setParameter("login", email).uniqueResult();
                
                user.setId(id);
            }
             hSession.update(user);
        }

        hSession.getTransaction().commit();

    }

    private Boolean identify(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();

        String email = request.getParameter("email");
        String pass = request.getParameter("pass");

        hSession.beginTransaction();
        Usuario user = (Usuario) hSession.createQuery("from Usuario as "
                + "c where c.login =:login and c.password =:pass").setParameter("login", email).setParameter("pass", pass).uniqueResult();
        hSession.getTransaction().commit();
        if (user != null) {
            session.setAttribute("user", user);
            return true;
        } else {
            return false;
        }
    }

    private void editUsuario(HttpServletRequest request) {
        String edit = request.getParameter("edit");
        HttpSession session = request.getSession();
        Usuario usuario = new Usuario();
        if (edit != null) {
            if (edit.equals("yes")) {
                Usuario user = (Usuario) session.getAttribute("user");
                usuario = user;
            } else {
                Integer user = Integer.parseInt(edit);

                Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
                hSession.beginTransaction();
                usuario = (Usuario) hSession.get(Usuario.class, user);
            
                hSession.getTransaction().commit();
            }
        }
        session.setAttribute("usuario", usuario);
    }

    private void deletarUsuario(HttpServletRequest request) {
        Integer user = Integer.parseInt(request.getParameter("un"));

        Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
        hSession.beginTransaction();
        Usuario u = (Usuario) hSession.get(Usuario.class, user);
        hSession.delete(u);
        hSession.getTransaction().commit();

    }

    private static ArrayList listUsers() {
        Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
        ArrayList<Usuario> usuarios;
        hSession.beginTransaction();

        usuarios = (ArrayList) hSession.createQuery("FROM Usuario").list();

        hSession.getTransaction().commit();

        return usuarios;
    }

    private void logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.removeAttribute("myrecs");
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
